#!/bin/bash

#Lanzando brokers
echo "Lanzando configurador"


######preguntar por por el rpc server
#si....levantar server
#no....pedir direccion

RPC="zzzz"
while [ $RPC != 's' ] && [ $RPC != 'n' ]; do
	echo "Desea correr el servidor RPC (s/n)"
	read RPC
done

RPC_IP="127.0.0.1"

if [ $RPC = 's' ];then
	#lanzarRPC
	cd out/rpcserver
	
	#sudo rpcbind 2> null
	sudo ./launcher_rpcserver
	
	cd ..
	cd ..
	
else
	#pedir direccion ip
	echo "Ingrese ID del servidor RPC"
	read RPC_ID_BROKER

	cd out/broker

	SEP="="
	IFS="
"
	LIST=$(cat brokerlist)
	for i in $LIST; do
		ID=$(echo  "$i"| cut -d "${SEP}" -f 1)
		IP=$(echo  "$i"| cut -d "${SEP}" -f 2)
		if [ $ID = $RPC_ID_BROKER ];then
			echo "IP del broker: $IP"
			RPC_IP=$IP
			sleep 1
			
		fi
	done
	cd ..
	cd ..


fi


######id de brokers

ANILLO=0
SIG=0

UNICO="zzzz"
while [ $UNICO != 's' ] && [ $UNICO != 'n' ]; do
	echo "Unico broker (s/n)"
	read UNICO
done

if [ $UNICO = 's' ];then
	ANILLO=1
	SIG=1
	BROKER="1"
	
else
	#ver que broker se tiene que levantar

	IP_BROKER=$(hostname --all-ip-addresses)
	
	cd out/broker

	SEP="="
	IFS="
"
	LIST=$(cat brokerlist)
	for i in $LIST; do
		ID=$(echo  "$i"| cut -d "${SEP}" -f 1)
		IP=$(echo  "$i"| cut -d "${SEP}" -f 2)
		echo "$ID"
		echo "$IP"
		if [ "$IP " = "$IP_BROKER" ];then
			BROKER="$ID"
			
		fi
	done
	cd ..
	cd ..

	echo "soy el broker $BROKER con IP $IP_BROKER"


	#preguto anillouuid
	while [ $ANILLO -lt 1 ] || [ $ANILLO -gt 100 ]; do
		echo "Id del anillo (1-100)"
		read ANILLO
	done
	#pregunto anilloSiguiente
	while [ $SIG -lt 1 ] || [ $SIG -gt 5 ]; do
		echo "Id del siguiente broker (1-5)"
		read SIG
	done
fi


##########configuro el config.ini
echo "***Configuraciones***"
echo "rpcserver=$RPC_IP" |tee ./out/broker/config.ini
echo "defaultbroker=127.0.0.1" |tee -a ./out/broker/config.ini
echo "puertoEntrada=20002" |tee -a ./out/broker/config.ini
echo "puertoSalida=20003" |tee -a ./out/broker/config.ini
echo "brokerId=$BROKER" |tee -a ./out/broker/config.ini
echo "AnilloUUID=$ANILLO" |tee -a ./out/broker/config.ini
echo "AnilloSiguiente=$SIG" |tee -a ./out/broker/config.ini

echo ""
echo ""
echo "***Lanzando broker***"
sleep 2

#lanzo el broker local
cd out/broker
./launcher_broker
cd ..
cd ..

######lanzo los forwarders contra los brokers externos
#echo ""
#echo ""
#echo "****Estableciendo canales entre brokers****"
sleep 2

cd out/broker

SEP="="
IFS="
"
LIST=$(cat brokerlist)
for i in $LIST; do
	ID=$(echo  "$i"| cut -d "${SEP}" -f 1)
	IP=$(echo  "$i"| cut -d "${SEP}" -f 2)
	if [ "$ID" != "$BROKER" ] && [ "$UNICO" = 'n' ];then
		echo ""
		echo "Estableciendo canales contra broker $ID"
		sleep 1
		./forwarder $ID $IP
	fi
done
cd ..
cd ..


 



